<template>
	<view>
		<!--<z-nav-bar>面授课程</z-nav-bar>-->
		<!--<public-module></public-module>-->
		<view class="QS-tabs-box">
			<QSTabs 
			ref="tabs" 
			:tabs="tabs" 
			animationMode="line3" 
			:current="current" 
			@change="change"
			activeColor="#000"
			lineColor="#81B435"
			swiperWidth="750">
			</QSTabs>
		</view>
		<swiper 
		:style="{'height': '100vh','padding-bottom': '100px'}" 
		:current="swiperCurrent" 
		@transition="transition"
		@animationfinish="animationfinish">
			<swiper-item class="swiper-item" v-for="(item, index) in tabsDetail" :key="index">
				<scroll-view scroll-y style="height: 100%;width: 100%;background: #f7f8fa;padding: 16px;">
					<view class="scroll-items">
						<base-banner :banners="[{type: '2', img: (item.imgUrl!=undefined?(defaultUrl + item.imgUrl): defaultImg), url: '' } ]" small/>
						<view class="item-name">
							{{item.modelName}}
						</view>
						<view class="item-update-time">
							更新日期 {{item.updateTime}}
						</view>
					</view>
					<view class="scroll-items" style="margin-top: 16px;">
						<view class="item-title">课程详情</view>
						<view class="item-list">
							<view class="list-item">
								<view class="list-item-title">价格：</view>
								<view class="list-item-cont">{{item.price}}元</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">课程结构：</view>
								<view class="list-item-cont">{{item.courseStructure}}</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">基础课轮数：</view>
								<view class="list-item-cont">{{item.maxSelectTimes}}</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">升学率：</view>
								<view class="list-item-cont">{{item.medical}}%</view>
							</view>
							<!--
							<view class="list-item">
								<view class="list-item-title">集训上课老师：</view>
								<view class="list-item-cont">{{item.teachUserName}}</view>
							</view>
							-->
							<view class="list-item">
								<view class="list-item-title">课下辅导：</view>
								<view class="list-item-cont">{{ selectDictLabel(afterTutoringTypeOptions, item.afterTutoringType)}}</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">集训吃住宿费：</view>
								<view class="list-item-cont">{{item.otherFee}}元</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">协议保障：</view>
								<view class="list-item-cont">{{selectDictLabel(protocolTypeOptions, item.protocolType)}}</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">教辅资料更换：</view>
								<view class="list-item-cont">{{selectDictLabel(freeBookFlagOptions, item.freeBookFlag)}}</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">填报志愿指导：</view>
								<view class="list-item-cont">{{selectDictLabel(voluntaryGuidTypeOptions, item.voluntaryGuidType)}}</view>
							</view>
							<view class="list-item">
								<view class="list-item-title">题库权限：</view>
								<view class="list-item-cont">{{selectDictLabel(queTypeOptions, item.queType)}}</view>
							</view>
							<view class="list-item">
								<view class="list-item-title"> 教辅资料：</view>
								<view class="list-item-cont">{{item.materials}}</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		<view class="footer">
			<!-- <navigator class="btn" url='/subpages/home/paysuccess'>我要报名（{{tabsDetail[swiperCurrent].price}}元）</navigator> -->
			<!-- <button type="primary" class="btn" @click="submitForm">新增停课申请</button> -->
			<button type="primary" class="btn" @click="submitForm">我要报名（{{tabsDetail[swiperCurrent].price}}元）</button>
		</view>
		<mask v-if='showMask'></mask>
	</view>
</template>

<script>
	import QSTabs from '@/components/QS-tabs/QS-tabs.vue';
	import mask from '@/components/mask/index.vue';
	import base from '@/config/baseUrl';
	
	const Sys = uni.getSystemInfoSync();
	const wH = Sys.windowHeight;
	let n = 1;
	export default {
		components: {
			QSTabs,
			mask
		},
		data() {
			return {
				defaultUrl: base.baseUrl,
				defaultImg: require('@/static/banner/small-banner.png'),
				tabs:[],
				tabsDetail:[{},{},{},{},{},{},{},{},{},{},{},{},{}],
				current: 0,
				swiperCurrent: 0,
				tabsHeight: 0,
				dx: 0,
				index: 0,
				showMask: true,
				afterTutoringTypeOptions: [],
				protocolTypeOptions: [],
				voluntaryGuidTypeOptions: [],
				queTypeOptions: [],
				freeBookFlagOptions: [],
			}
		},
		onLoad() {
			this.$api.common.getDict("edu_after_tutoring_type").then(res => {
				this.afterTutoringTypeOptions = res.data
			})
			this.$api.common.getDict("edu_protocol_type").then(res => {
				this.protocolTypeOptions = res.data
			})
			this.$api.common.getDict("edu_voluntary_guid_type").then(res => {
				this.voluntaryGuidTypeOptions = res.data
			})
			this.$api.common.getDict("edu_que_type").then(res => {
				this.queTypeOptions = res.data
			})
			this.$api.common.getDict("exam_free_book_flag").then(res => {
				this.freeBookFlagOptions = res.data
			})
		},
		async created () {
			await this.init()
			let curPage = this.getCurPage()
			//在微信小程序或是app中，通过curPage.options；如果是H5，则需要curPage.$route.query（H5中的curPage.options为undefined，所以刚好就不需要条件编译了）
			let curParam = curPage.options || curPage.$route && curPage.$route.query
			console.log(curParam.index)
			this.index = curParam.index
			this.current = curParam.index
			console.log(curParam.index)
			this.change(curParam.index)
		},
		// async onLoad(option) {
		//     this.index=JSON.parse(decodeURIComponent(option.index))
		// 	console.log(this.index, 'index')
		// 	this.swiperCurrent = this.index;
		// },
		methods: {
			getCurPage(){
			    let pages = getCurrentPages()
			    let curPage = pages[pages.length-1]
				console.log(curPage, 'console.log(curPage)')
			    return curPage
			},
			async init () {
				let res = await this.$api.model.getModelList()
				if (res && res.data) {
					this.tabs = []
					this.modelList = res.data
					res.data.forEach(e => {
						this.tabs.push(e.modelName)
					})
				}
				this.current = this.index
				// this.change(this.index)
			},
			async submitForm() {
				try {
					let _this = this
					// uni.navigateTo({
					// 	url: '/subpages/home/paysuccess?actualPrice=' + this.tabsDetail[this.index].price +'&&modelId=' + this.tabsDetail[this.index].modelId,
					// });
					let param = {
						userId: this.$store.state.userInfo.userId,
						consignee: this.$store.state.userInfo.nickName,
						mobile: '15220112108',
						goodsPrice: this.tabsDetail[this.index].price,
						orderPrice: this.tabsDetail[this.index].price,
						actualPrice: this.tabsDetail[this.index].price,
						mallOrderGoodsList: [
							{
								goodsName: this.tabsDetail[this.index].modelName
							}
						]
					}
					let res = await this.$api.order.createRegistOrder(param)
					console.log(res)
					if (res.code == 200) {
						let actualPrice = res.data.actualPrice
						let orderParams = {
							userId: this.$store.state.userInfo.userId,
							orderId: res.data.orderId
						}
						let preRes = await this.$api.order.prepay(orderParams)
						//console.log(JSON.stringify(preRes))
						uni.requestPayment({
							provider: 'wxpay',
							//timeStamp: String(Date.now()),
							//nonceStr: this.randomString(),
							timeStamp: preRes.data.timeStamp,
							nonceStr: preRes.data.nonceStr,
							package: preRes.data.packageValue,
							signType: preRes.data.signType,//'MD5',
							paySign: preRes.data.paySign,
							success: function(res) {
								console.log('success:' + JSON.stringify(res));
								uni.navigateTo({
									url: '/subpages/home/paysuccess?actualPrice=' + actualPrice +'&&modelId=' + this.tabsDetail[this.index].modelId,
								});
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
							}
						});
					}
				}  catch (e) {
					console.log(e, '支付错误信息')
					uni.showToast({
						title: '支付失败',
						icon: "none"
					})
				} 
				// createRegistOrder
				// let param ={
				// 			userId: _this.data.cardId,
				// 			orderId: _this.shopId 
				// 		}
				// uni.navigateTo({
				// 	url: 'subpages/home/paysuccess'
				// });
			},
			randomString(len) {
				  len = len || 32;
				  // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
				  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
				  var maxLen = $chars.length;
				  var str = '';
				  for (var i = 0; i < len; i++) {
					  str += $chars.charAt(Math.floor(Math.random() * maxLen));
				 }
				 return str;
			 },
			async change(index) {
				this.swiperCurrent = index
				let modelId = this.modelList[index].modelId
				try {
					let res = await this.$api.model.getModelDetail(modelId)
					this.tabsDetail.splice(index, 1, res.data)
					//console.log(JSON.stringify(this.tabsDetail))
					/*
					this.smallBanners = [
						{
							type: '2',
							img: require('@/static/banner/banner-jl1.png'),
							url: '/subpages/home/template'
						}
					]
					*/
					// setTimeout(() => {
					// 	this.showMask = false
					// }, 1000)
					this.$nextTick(()=> {
						this.showMask = false
					})
				} catch (e) {
					uni.showToast({
						title: '获取数据失败',
						icon: "none"
					})
				}
			},
			transition({ detail: { dx } }) {
				this.$refs.tabs.setDx(dx);
				console.log(dx, 'dx')
				// this.change(dx)
			},
			animationfinish({detail: { current }}) {
				this.$refs.tabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
			},
			// 以下方法请配置成公共方法
			selectDictLabel(datas, value) {
				var actions = [];
				Object.keys(datas).some((key) => {
					if (datas[key].dictValue == ('' + value)) {
						actions.push(datas[key].dictLabel);
						return true;
					}
				})
				return actions.join('');
			}
		}
	}
</script>

<style scoped>
	.QS-tabs-box{
		width: 100%;
		position: sticky;
		top: 0;
		z-index: 10;
		background-color: white;
	}
	.swiper-item{
		background-color: #fff;
	}
	.scroll-items{
		display: flex;
		flex-direction: column;
		width: 100%;
		padding: 40rpx;
	}
	.scroll-item{
		margin-top: 15rpx;
		padding: 25rpx;
		background-color: white;
		border-radius: 8rpx;
		width: 100%;
		display: flex;
		flex-direction: row;
		border: 1px solid #f8f8f8;
	}
	.scroll-item-image-box{
		flex-grow: 0;
	}
	.scroll-item-text-box{
		flex-grow: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		font-size: 28rpx;
		font-weight: bold;
		margin-left: 15rpx;
	}
	.scroll-item-image{
		border-radius: 4rpx;
		width: 180rpx;
		height: 150rpx;
	}
	.scroll-items {
		background: #fff;
		border-radius: 8px;
		padding: 0px 0px 20px;
	}
	.item-name {
		font-size: 17px;
		line-height: 20px;
		color: #323233;
		margin-top: 12px;
		margin-left: 16px;
	}
	.item-update-time {
		font-size: 13px;
		line-height: 13px;
		color: #969696;
		margin-top: 8px;
		margin-left: 16px;
	}
	/deep/.banner-wrap {
		margin: 0 !important;
	}
	/deep/.banner-wrap .swiper-box.small .swiper-item image {
		width: 100% !important;
	}
	.item-title {
		font-size: 17px;
		line-height: 20px;
		color: #323233;
		margin-top: 12px;
		margin-left: 16px;
		position: relative;
		margin-bottom: 10px;
	}
	.item-title::after {
		content: '';
		width: 32px;
		height: 3px;
		left: 0px;
		top: 28px;
		background-color: #F5F5F5;
		position: absolute;
	}
	.list-item {
		margin-top: 14px;
		vertical-align: top;
	}
	.list-item-cont {
		display: inline-block;
		width: 66%;
		font-size: 13px;
		line-height: 16px;
		color: #323232;
		vertical-align: inherit;
	}
	.list-item-title {
		width: 33%;
		text-align: right;
		display: inline-block;
		font-size: 13px;
		line-height: 16px;
		text-align: right;
		color: #969696;
		vertical-align: inherit;
	}
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 99;
		height: 99px;
		width: 100%;
		background: #F7F8FA;
	}
	.btn {
		margin: 8px 16px;
		background: #81B435;
		height: 49px;
		text-align: center;
		line-height: 49px;
		color: #fff;
		font-size: 16px;
		border-radius: 25px;
	}
</style>
